package com.scape.core.web;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import com.scape.core.model.Document;

@RooWebScaffold(path = "documents", formBackingObject = Document.class,  update=false , exposeJson=true)
@RequestMapping("/documents")
@Controller
public class DocumentController 
{
	private static final Log log = LogFactory.getLog(DocumentController.class);
	private static transient String applicationBase = null;

	@InitBinder
	protected void initBinder(HttpServletRequest request,
	                       ServletRequestDataBinder binder)
	                   throws ServletException 
	{
	    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
	    fetchApplicationBase(request);
	}
	
	@RequestMapping(value="/createFromJson" , method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json) {
        HttpHeaders headers= new HttpHeaders();
        headers.add("Content-Type", "application/text");
        Document doc = Document.fromJsonToDocument(json);
        if (doc == null || doc.getId() == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        doc.persist();
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

	@RequestMapping(value="savedoc",  method = RequestMethod.POST)
	public @ResponseBody String createdoc(HttpServletRequest request) {
			Document document = new Document();
			document.setFilename(request.getHeader("X-File-Name"));
			InputStream is = null;
	        FileOutputStream fos = null;
	        try {
	            is = request.getInputStream();
	            fos = new FileOutputStream(new File(Document.SAVE_PATH, request.getHeader("X-File-Name")));
	            IOUtils.copy(is, fos);
	        } catch (FileNotFoundException ex) {
	            return " {success:false}";
	        } catch (IOException ex) {
	            return " {success:false}";
	        } finally {
	            try {
	                fos.close();
	                is.close();
	            } catch (IOException ignored) {
	            }
	        }
	        return " {success:true}";
	    }
	
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable("id") Long id, Model model) 
	{
	        Document doc = Document.findDocument(id); 
	        //TODO:  Need to Fix this and remove the hard coding
	        doc.setUrl("http://localhost:8080/InventoryApp/documents/showdoc/"+id);
	        model.addAttribute("document", Document.findDocument(id));
	        model.addAttribute("itemId", id);
	        return "documents/show";
	}
	 
	@RequestMapping(value = "/showdoc/{id}", method = RequestMethod.GET)
	public String showdoc(  @PathVariable("id") Long id,
	                    HttpServletResponse response,
	                    Model model) {
	   Document doc = Document.findDocument(id);
	 
	   try {
	          response.setHeader("Content-Disposition", "inline;filename=\"" +doc.getFilename()+ "\"");
	 
	          OutputStream out = response.getOutputStream();
	          response.setContentType(doc.getContentType());
	          IOUtils.copy( new ByteArrayInputStream(doc.getContent()),out);
	            out.flush();
	 
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return null;
	    }

	   
    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
    	Document document= Document.findDocument(id);
    	
    	document.setUrl(applicationBase+"/documents/showdoc/"+id);
        model.addAttribute("document", document);
        return "documents/update";
    }
    
    
    public static void fetchApplicationBase(HttpServletRequest req) {
        if (applicationBase == null) {
            applicationBase = req.getScheme() + "://" + req.getServerName() +
                    getPort(req) + req.getContextPath();
        }
    }

    private static String getPort(HttpServletRequest req) {
        if ("http".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 80 ||
                "https".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 443 ) {
            return (":" + req.getServerPort());
        } else {
            return "";
        }
    }
}
